import React, { useState, useEffect } from 'react';
import { Card, Button, InputNumber, Space, Table, message, Tooltip } from 'antd';
import { PlusOutlined, CopyOutlined, GiftOutlined, DeleteOutlined } from '@ant-design/icons';
import { createInvitation, batchCreateInvitations, getInvitations, deleteInvitation } from '../../api/admin';
import type { InvitationCode } from '../../types';

const InvitationManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [batchLoading, setBatchLoading] = useState(false);
  const [tableLoading, setTableLoading] = useState(false);
  const [batchCount, setBatchCount] = useState(5);
  const [invitations, setInvitations] = useState<InvitationCode[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  useEffect(() => {
    loadInvitations();
  }, []);

  const loadInvitations = async (page = 1, size = 10) => {
    setTableLoading(true);
    try {
      const response = await getInvitations({ page, size });
      if (response.code === 200) {
        setInvitations(response.data.records);
        setPagination({
          current: response.data.current,
          pageSize: response.data.size,
          total: response.data.total,
        });
      } else {
        message.error(response.message || '获取邀请码列表失败');
      }
    } catch (error) {
      message.error('获取邀请码列表失败，请稍后重试');
    } finally {
      setTableLoading(false);
    }
  };

  const handleCreateSingle = async () => {
    setLoading(true);
    try {
      const response = await createInvitation();
      if (response.code === 200) {
        message.success('邀请码创建成功');
        await loadInvitations(pagination.current, pagination.pageSize);
      } else {
        message.error(response.message || '创建失败');
      }
    } catch (error) {
      message.error('创建失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleBatchCreate = async () => {
    if (batchCount < 1 || batchCount > 50) {
      message.error('批量创建数量应在1-50之间');
      return;
    }

    setBatchLoading(true);
    try {
      const response = await batchCreateInvitations(batchCount);
      if (response.code === 200) {
        message.success(`成功创建 ${response.data.length} 个邀请码`);
        await loadInvitations(pagination.current, pagination.pageSize);
      } else {
        message.error(response.message || '批量创建失败');
      }
    } catch (error) {
      message.error('批量创建失败，请稍后重试');
    } finally {
      setBatchLoading(false);
    }
  };

  const copyToClipboard = async (code: string) => {
    try {
      await navigator.clipboard.writeText(code);
      message.success('邀请码已复制到剪贴板');
    } catch (error) {
      // 降级方案
      const textArea = document.createElement('textarea');
      textArea.value = code;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand('copy');
        message.success('邀请码已复制到剪贴板');
      } catch (err) {
        message.error('复制失败，请手动复制');
      }
      document.body.removeChild(textArea);
    }
  };

  const handleDelete = async (id: number) => {
    setTableLoading(true);
    try {
      const response = await deleteInvitation(id);
      if (response.code === 200) {
        message.success('邀请码删除成功');
        await loadInvitations(pagination.current, pagination.pageSize);
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      message.error('删除失败，请稍后重试');
    } finally {
      setTableLoading(false);
    }
  };

  const columns = [
    {
      title: '邀请码',
      dataIndex: 'code',
      key: 'code',
      render: (code: string) => (
        <Space>
          <code style={{ 
            padding: '2px 6px', 
            backgroundColor: '#f5f5f5', 
            borderRadius: '4px',
            fontFamily: 'monospace'
          }}>
            {code}
          </code>
          <Tooltip title="复制邀请码">
            <Button 
              type="text" 
              icon={<CopyOutlined />} 
              size="small"
              onClick={() => copyToClipboard(code)}
            />
          </Tooltip>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'used',
      key: 'used',
      render: (used: boolean, record: InvitationCode) => {
        // 优先使用used字段，如果不存在则使用isUsed字段，最后检查status字段
        const isUsed = used !== undefined ? used : (record.isUsed !== undefined ? record.isUsed : record.status === 1);
        return (
          <span style={{ 
            color: isUsed ? '#ff4d4f' : '#52c41a',
            fontWeight: 'bold'
          }}>
            {isUsed ? '已使用' : '未使用'}
          </span>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      render: (time: string, record: InvitationCode) => {
        // 优先使用createdTime字段，如果不存在则使用createTime字段
        const createTime = time || record.createTime;
        if (!createTime) return '-';
        
        try {
          return new Date(createTime).toLocaleString();
        } catch (error) {
          console.error('日期格式错误:', createTime);
          return createTime;
        }
      },
    },
    {
      title: '使用者',
      dataIndex: 'usedByUsername',
      key: 'usedByUsername',
      render: (username: string) => username || '-',
    },
    {
      title: '使用时间',
      dataIndex: 'usedTime',
      key: 'usedTime',
      render: (time: string) => {
        if (!time) return '-';
        
        try {
          return new Date(time).toLocaleString();
        } catch (error) {
          console.error('日期格式错误:', time);
          return time;
        }
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (text: string, record: InvitationCode) => {
        // 已使用的邀请码不能删除
        const isUsed = record.used !== undefined ? record.used : (record.isUsed !== undefined ? record.isUsed : record.status === 1);
        
        return (
          <Space>
            {!isUsed ? (
              <Button 
                type="text" 
                icon={<DeleteOutlined />} 
                size="small"
                danger
                onClick={() => handleDelete(record.id)}
              >
                删除
              </Button>
            ) : (
              <Tooltip title="已使用的邀请码不能删除">
                <Button 
                  type="text" 
                  icon={<DeleteOutlined />} 
                  size="small"
                  disabled
                >
                  删除
                </Button>
              </Tooltip>
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <h2>邀请码管理</h2>
      
      <Card style={{ marginBottom: 24 }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <div>
            <h3>创建邀请码</h3>
            <Space wrap>
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                loading={loading}
                onClick={handleCreateSingle}
              >
                创建单个邀请码
              </Button>
              
              <Space.Compact>
                <InputNumber
                  min={1}
                  max={50}
                  value={batchCount}
                  onChange={(value) => setBatchCount(value || 5)}
                  style={{ width: 120 }}
                  placeholder="数量"
                />
                <Button 
                  type="primary" 
                  icon={<GiftOutlined />}
                  loading={batchLoading}
                  onClick={handleBatchCreate}
                >
                  批量创建
                </Button>
              </Space.Compact>
            </Space>
          </div>
          
          <div style={{ fontSize: '12px', color: '#666' }}>
            <p>• 单次最多可批量创建50个邀请码</p>
            <p>• 每个邀请码只能使用一次</p>
            <p>• 已使用的邀请码无法再次使用</p>
          </div>
        </Space>
      </Card>

      <Card title={`邀请码列表 (${pagination.total})`}>
        <Table
          columns={columns}
          dataSource={invitations}
          rowKey="id"
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, pageSize) => loadInvitations(page, pageSize),
            onShowSizeChange: (current, size) => loadInvitations(current, size),
          }}
          scroll={{ x: 800 }}
          loading={tableLoading}
        />
      </Card>
    </div>
  );
};

export default InvitationManagement; 